<?php

namespace app\pay\controller;

use app\pay\model\User;
use think\Controller;
use think\Db;
use app\pay\service\Hqkjsk;

class Payhqkj extends Base
{
	/**
	 * 商户注册  储蓄卡
	 * @Author tw
	 * @Date   2018-09-29
	 * @return [type]     [description]
	 */
	public function register($pay_id = '', $uid = '', $cid = "")
	{
		if (empty($pay_id) || empty($uid)) {
			return ['error' => 1, 'msg' => '参数错误'];
		}
		$payment_public = $this->payment_public($pay_id, $uid, $cid, 'jskj_', 1, 2);
		//halt($payment_public);
		if ($payment_public['error'] != 0) {
			return $payment_public;
		}

		//halt($payment_public);
		$payment_user = $payment_public['payment_user'];
		$user = $payment_public['user'];
		$user_rate_sk = $payment_public['user_rate_sk'];
		//更新费率
		$user_rate_sk["rate_rate"] = (new User())->getUserPayrecordsRankConfig($user["user_type_id"]);
		//取得银行信息
		$sk_card = Db::name('user_card')
			->where(['card_uid' => $uid, 'card_type' => 2, 'card_blocked' => 0])
			->find();
		if (empty($sk_card)) {
			return ['error' => 1, 'msg' => '结算卡不存在'];
		}
		$bank = Db::name("bank_list")->find($sk_card["card_bank_id"]);

		//接口1：商户接口报件
		$param = [
			"ordersn" => $payment_user["user_number"],//流水号
			"dsorderid" => $payment_user["user_number"],//商户订单号
			"futureRateValue" => (string)($user_rate_sk["rate_rate"] * 100),//每笔费率
			"fixAmount" => "200",//单笔价格
			"accountName" => $sk_card['card_name'],//真实姓名
			"idcard" => $user['user_idcard'],//身份证号
			"mobile" => $sk_card['card_phone'],//预留手机号

			"settleBankCard" => $sk_card["card_no"],//收款银行卡号
			"settleBankName" => $bank["list_name"],//收款银行卡名称:民生银行
			"settleBankCode" => $bank["list_code"],//银行代码:CMBC
		];
		//halt($param);
		$regRes = (new Hqkjsk)->register($param);
		//halt($regRes);
		unset($param);
		if ($regRes["returncode"] == "0000" || $regRes["returncode"] == "0052") {//03008法人身份信息重复进件
			$this->payment_register($payment_user, 1, $regRes["errtext"], $regRes['subMerchantNo']);
			return ['error' => 0, 'msg' => '入驻成功'];
		} else {
			return ['error' => 1, 'msg' => "商户注册失败：" . $regRes["errtext"]];
		}
	}


	/**
	 * 修改卡号和费率
	 * @Author tw
	 *
	 * @param string $pay_id [description]
	 * @param string $uid [description]
	 *
	 * @return [type]         [description]
	 */
	public function update_fee($pay_id = '', $uid = '')
	{
		if (empty($pay_id) || empty($uid)) {
			return ['error' => 1, 'msg' => '参数错误'];
		}
		$payment_public = $this->payment_public($pay_id, $uid, '', 2, 2);

		if ($payment_public['error'] != 0) {
			return $payment_public;
		}
		$payment_user = $payment_public['payment_user'];
		$user = $payment_public['user'];
		$user_rate_sk = $payment_public['user_rate_sk'];
		//更新费率
		$user_rate_sk["rate_rate"] = (new User())->getUserPayrecordsRankConfig($user["user_type_id"]);
		//取得银行信息
		$sk_card = Db::name('user_card')
			->where(['card_uid' => $uid, 'card_type' => 2, 'card_blocked' => 0])
			->find();
		if (empty($sk_card)) {
			return ['error' => 1, 'msg' => '结算卡不存在'];
		}
		$bank = Db::name("bank_list")->find($sk_card["card_bank_id"]);




		//接口1：商户接口报件
		$param = [
			"ordersn" => $payment_user["user_number"],//流水号
			"dsorderid" => $payment_user["user_number"],//商户订单号
			"subMerchantNo" => $payment_user["user_merchant"],//子商户号
			"futureRateValue" => $user_rate_sk["rate_rate"] * 100,//每笔费率
			"fixAmount" => 200,//单笔价格

			"settleBankCard" => $sk_card["card_no"],//收款银行卡号
			"settleBankName" => $bank["list_name"],//收款银行卡名称:民生银行
			"settleBankCode" => $bank["list_code"],//收款银行卡代码:CMBC
			"accountName" => $sk_card['card_name'],//收款人姓名
			"mobile" => $sk_card['card_phone'],//收款手机号
		];

		$res = (new Hqkjsk)->updateFee($param);
		if ($res['returncode'] == '0000') {
			return ['error' => 0, 'msg' => '修改成功'];
		} else {
			return ['error' => 1, 'msg' => $res['errtext']];
		}
	}


	/**
	 * 扣款
	 *
	 * @param string $pay_id 【渠道id】
	 * @param string $uid 【用户id】
	 * @param string $cid 【银行卡id】
	 * @param string $id 【收款列表信息id】
	 *
	 * @return array
	 */
	public function pay($pay_id = '', $uid = '', $cid = '', $id = '')
	{
		if (empty($pay_id) || empty($uid) || empty($cid) || empty($id)) {
			return ['error' => 1, 'msg' => '参数错误'];
		}
		$pay_records = Db::name('pay_records')->where('records_id', $id)->where('records_uid', $uid)->where('records_pay_cid', $cid)->find();
		if (empty($pay_records)) {
			return ['error' => 1, 'msg' => '订单错误'];
		} elseif ($pay_records['records_state'] != 0) {
			return ['error' => 1, 'msg' => '请重新提交支付'];
		}
		$payment_public = $this->payment_public($pay_id, $uid, $cid, '', 2, 2);

		if ($payment_public['error'] != 0) {
			return $payment_public;
		}
		$payment_user = $payment_public['payment_user'];
		$card = $payment_public['card'];
		$user = $payment_public['user'];
		$user_rate_sk = $payment_public['user_rate_sk'];

		//接口：修改卡号和费率
		$param = [
			"ordersn" => get_order_sn("", $uid),//流水号
			"dsorderid" => $pay_records['records_form_no'],//商户订单号
			"subMerchantNo" => $payment_user["user_merchant"],//子商户号
			"amount" => (string)($pay_records['records_money'] * 100),//交易金额
			"bankcard" => $card['card_no'],//消费银行卡号
			"accountName" => $card['card_name'],//真实姓名
			"mobile" => $card['card_phone'],//消费卡手机号
			"cvn2" => $card['card_cvn'],//消费银行卡的cvn2
			"expireDate" => $card['card_exp_date'],//消费银行卡的有效期
			"returnUrl" => config("app_host") . '/pay/Payhqkj/callback',//前台通知地址
			"notifyUrl" => config("app_host") . '/pay/Payhqkj/pay_notify',//后台异步通知地址
		];
		$res = (new Hqkjsk)->pay($param);
		$this->pay_logs(json_encode($param), json_encode($res), 'Payhqkj', 'pay');

		// $res ='{"transcode":"026","merchno":"erzd2018100901","dsorderid":"KJ1810275597095004567","sign":"da84e1d53a15b0c3189181ac58fd6c87","ordersn":"1810275769097004512","returncode":"0000","errtext":"下单成功","orderid":"2018102722363600100156671","amount":"50000","transtype":"18","pay_info":"http://pay.huanqiuhuiju.com/authsys/api/tl/bindCardPage.do","pay_code":"{\"orderid\":\"2018102722363600100156671\",\"merchno\":\"erzd2018100901\",\"bankcard\":\"62257888 **** 1197\",\"accountName\":\"王*月\",\"mobile\":\"133 **** 8078\",\"returnUrl\":\"http://shenyang.sdshengyixing.com/pay/Payhqkj/callback\",\"notifyUrl\":\"http://shenyang.sdshengyixing.com/pay/Payhqkj/pay_notify\",\"sign\":\"5b943e922649aeab8f789da245c51038\"}"}';
		if ($res['returncode'] != '0000') {
			$this->payment_kj($id, $uid, 2, $res['transtype'], '', $res['errtext'], json_encode($res), "");
			return ['error' => 1, 'msg' => $res['errtext']];
		}
		$this->payment_kj($id, $uid, 3, $res['transtype'], '', $res['errtext'], json_encode($res), "");
		$url = 'http://' . $_SERVER['HTTP_HOST'] . '/pay/Payhqkj/webpay/id/' . $id;
		return ['error' => '10', 'msg' => '支付跳转', 'type' => 'web', 'title' => '支付', 'url' => $url];

	}

	public function webpay()
	{
		$id = input('param.id');
		$pay_records = Db::name('pay_records')->where('records_id', $id)->find();
		if (empty($pay_records)) {
			return json(['error' => 1, 'msg' => '订单不存在']);
		}
		$obj = json_decode($pay_records['records_info'], true);
		$pay_code = json_decode($obj['pay_code'], true);

		$formHtml = '<form method="post" id="myform" name="myform" action="' . $obj['pay_info'] . '">';
		foreach ($pay_code as $key => $value) {
			$formHtml .= '<input type="hidden" name="' . $key . '" value="' . urldecode($value) . '">';
		}
		// echo '<input type="submit" value="提交表单">';
		$formHtml .= '</form><script type="text/javascript">document.myform.submit()</script>';
		echo $formHtml;
		exit;
	}


	/**
	 * 支付返回
	 */
	public function callback()
	{
		$post = input('post.');
		if (empty($post)) {
			echo '<h1>支付中,请稍后查看结果</h1>';
			exit;
			return json(['error' => 1, 'msg' => '参数错误']);
		}
		$this->notify_logs($post, 'Payhqkj', 'callback');

		$pay_records = Db::name('pay_records')->where('records_form_no', $post['dsorderid'])->find();
		if (empty($pay_records)) {
			return json(['error' => 1, 'msg' => '订单不存在']);
		} elseif ($pay_records['records_state'] != 3) {
			return json(['error' => 1, 'msg' => '订单不存在']);
		}
		if ($post['status'] != '00') {
			//支付失败
			$this->pay_records($pay_records['records_id'], $pay_records['records_uid'], 2, $obj['dsorderid']);
			echo "支付失败";
			exit();
		}
		$this->pay_records($pay_records['records_id'], $pay_records['records_uid'], 1, $obj['dsorderid']);
		echo "支付成功";
		exit();
	}

	/**
	 * 扣款回调
	 * @Author tw
	 * @Date   2018-10-09
	 * @return [type]     [description]
	 */
	public function pay_notify()
	{
		$post = input('post.');
		if (empty($post)) {
			return json(['error' => 1, 'msg' => '参数错误']);
		}
		$this->notify_logs($post, 'Payhqkj', 'pay_notify');


		$pay_records = Db::name('pay_records')->where('records_form_no', $post['dsorderid'])->find();
		if (empty($pay_records)) {
			return json(['error' => 1, 'msg' => '订单不存在']);
		} elseif ($pay_records['records_state'] != 3) {
			return 'SUCCESS';
		}
		if ($post['status'] != '00') {
			//支付失败
			$this->pay_records($pay_records['records_id'], $pay_records['records_uid'], 2, $post['dsorderid']);
		}
		$this->pay_records($pay_records['records_id'], $pay_records['records_uid'], 1, $post['dsorderid']);
		return 'SUCCESS';
	}

	/**
	 * 交易状态查询
	 *
	 * @param string $pay_records
	 *
	 * @return array
	 */
	public function query_order_status($pay_records = '')
	{
		$id = $pay_records['records_id'];
		$uid = $pay_records['records_uid'];
		$pay_id = $pay_records['records_pay_id'];

		if (empty($id) || empty($uid) || empty($pay_id) || empty($pay_records)) {
			return ['error' => 1, 'msg' => '参数错误'];
		}

		//查询接口
		$param = [
			"ordersn" => get_order_sn("", $uid),//流水号
			"dsorderid" => $pay_records['records_form_no'],//商户订单号
			"transtype" => $pay_records['records_form_up_no'],//交易类型
		];
		$res = (new Hqkjsk)->queryOrder($param);
		//halt($res);
		$this->pay_logs(json_encode($param), json_encode($res), 'Payhqkj', 'query_order_status');

		if ($res['returncode'] != '0000') {
			return ['error' => 1, 'msg' => $res['errtext']];
		}
		switch ($res['status']) {
			case '00':
				# 成功
				$this->payment_kj($id, $uid, 1, '', '', $res['message'], '', time());
				return ['error' => 0, 'msg' => '支付成功'];
				break;
			case '01':
				# 处理中
				// if(time() < (strtotime($pay_records['records_time'])+1200))
				// {
				//     $this->payment_kj($id,$uid,3,'','',$obj['message'],'');
				//     return ['error'=>1,'msg'=>'支付处理中'];
				// }
				// else
				// {
				//     $this->payment_kj($id,$uid,2,'','',$obj['message'],'',time());
				//     return ['error'=>1,'msg'=>'订单失败:'.$obj['message']];
				// }
				$this->payment_kj($id, $uid, 3, '', '', $res['message'], '');
				return ['error' => 1, 'msg' => '支付处理中'];
				break;
			case '02':
				# 失败
				$this->payment_kj($id, $uid, 2, '', '', $res['message'], '', time());
				return ['error' => 1, 'msg' => $res['message']];
				break;
			case '04':
				# 订单关闭
				$this->payment_kj($id, $uid, 2, '', '', $res['message'], '', time());
				return ['error' => 1, 'msg' => '订单关闭'];
				break;
			case '06':
				# 待代付
				$this->payment_kj($id, $uid, 4, '', '', $res['message'], '', time());
				return ['error' => 0, 'msg' => $res['message']];
				break;
			case '99':
				# 订单号不存在
				$this->payment_kj($id, $uid, 2, '', '', $res['message'], '', time());
				return ['error' => 1, 'msg' => $res['message']];
				break;
			default:
				$this->payment_kj($id, $uid, 2, '', '', $res['message'], '', time());
				return ['error' => 1, 'msg' => $res['errtext']];
				break;
		}

	}

	/**
	 * config json 转字符串[字符串格式：name:张三|time:20180116]
	 * @return [str] [字符串格式：name:张三|time:20180116
	 * @author yan  2018-01-17
	 */
	protected function jsonTostr($configstr)
	{
		$jsonarr = json_decode($configstr);
		$str2 = '';
		if ($jsonarr) {
			$json_main = array();
			foreach ($jsonarr as $arr1) {
				$str = implode(':', $arr1);
				$json_main[] = $str;
			}
			$str2 = implode('|', $json_main);
		}
		return $str2;
	}


	/**
	 * 商户注册查询
	 * @Author tw
	 *
	 * @param  [type] $uid            [description]
	 * @param  [type] $payment_config [description]
	 * @param  [type] $payment_user   [description]
	 * @param  [type] $user_idcard    [description]
	 * @param  [type] $type           [1更改失败状态]
	 *
	 * @return [type]                 [description]
	 */
	public function register_query($uid = '', $payment_config = '', $payment_user = '', $user_idcard = '', $type = '')
	{
		return ['error' => 0, 'msg' => '不支持查询'];
	}

	/**
	 * 支付确认
	 */
	public function pay_confirm()
	{
		return ['error' => 1, 'msg' => '参数错误'];
	}

	public function city_all()
	{
		return ['error' => 1, 'msg' => '不支持地区'];
	}

}